package com.sname.car.common.exception;

import com.sname.car.common.constants.Constants;
import com.sname.car.common.resp.ApiResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

/**
 * Created By  醉美柳舞之众星捧月
 *
 * @author songx
 * @date 2018/10/13 20:15
 */
@RestControllerAdvice
public class ExceptionHandleAdvice {
    /**
     * Author song  醉美柳舞之众星捧月
     * Date & Time  2018/10/13 20:17
     * Description  Controller层的全局异常处理
     */
    private final Logger log = LoggerFactory.getLogger(getClass());

    @ExceptionHandler(Exception.class)
    public ApiResult handleException(Exception e) {
        log.error(e.getMessage(), e);
        return new ApiResult(Constants.RESP_STATUS_INTERNAL_ERROR, "系统异常,请稍后再试!");
    }

    @ExceptionHandler(CarException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public ApiResult handleException(CarException e) {
        log.error(e.getMessage(), e);
        return new ApiResult(e.getStatusCode(), e.getMessage());
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ApiResult handleIllegalParamException(MethodArgumentNotValidException e) {
        List<ObjectError> errors = e.getBindingResult().getAllErrors();
        String message = "参数不合法";
        FieldError fieldError = (FieldError) errors;
        if (errors.size() > 0) {
            message = fieldError.getField() + "  " + errors.get(0).getDefaultMessage();
        }
        return new ApiResult(Constants.RESP_STATUS_INTERNAL_ERROR, message);
    }
}
